package com.juyu.miliao.api.service;

import com.alibaba.fastjson.JSONObject;
import com.juyu.miliao.api.dao.redis.DynamicCommentInfoRedisDao;
import com.juyu.miliao.api.dao.redis.DynamicInfoRedisDao;
import com.juyu.miliao.api.dao.redis.usercache.UserCacheVo;
import com.juyu.miliao.api.dao.redis.usercache.UserInfoCache;
import com.juyu.miliao.api.domain.CommentReplyInfo;
import com.juyu.miliao.api.domain.DynamicCommentInfo;
import com.juyu.miliao.api.domain.dto.CommentReplyInfoDTO;
import com.juyu.miliao.api.domain.vo.DynamicDetailInfoVo;
import com.juyu.miliao.api.domain.vo.DynamicSourceInfoVO;
import com.juyu.miliao.common.constant.EnumType;
import com.juyu.miliao.common.exception.ConsumeRuntimeException;
import com.juyu.miliao.common.netease.NetEaseCloudUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author xuanqicheng
 * @create 2019-21-15:35
 */
@Service
public class CommentReplyInfoService {

    private static final Logger logger = LoggerFactory.getLogger("dynamicCommentLog");

    @Autowired
    private DynamicCommentInfoRedisDao dynamicCommentInfoRedisDao;

    @Autowired
    private DynamicInfoRedisDao dynamicInfoRedisDao;

    @Autowired
    private UserInfoCache userInfoCache;

    @Autowired
    private VestRobotMessageService vestRobotMessageService;

    /**
     * 添加回复信息
     * @param commentReplyInfoDTO
     */
    public void addCommentReply(CommentReplyInfoDTO commentReplyInfoDTO) throws IOException {

        DynamicCommentInfo obj = dynamicCommentInfoRedisDao
                .getDynamciCommentInfoByCommentId(commentReplyInfoDTO.getCommentId());

        CommentReplyInfo commentReplyInfo = new CommentReplyInfo();

        BeanUtils.copyProperties(commentReplyInfoDTO,commentReplyInfo);

        commentReplyInfo.setReplyToUserId(obj.getFromUserId());

        String temp = NetEaseCloudUserService.getYunTextCheck(commentReplyInfoDTO.getReplyContent());

        logger.info("评论回复反垃圾响应内容："+temp+"，评论id："+commentReplyInfoDTO.getCommentId()
                +",评论回复内容："+commentReplyInfoDTO.getReplyContent());

        JSONObject json = JSONObject.parseObject(temp);

        int code = json.getIntValue("code");

        String msg = json.getString("msg");

        if(code == 200){
            JSONObject result = json.getJSONObject("result");
            int action = result.getIntValue("action");
            if(action==0){
                dynamicCommentInfoRedisDao.addCommentReply(commentReplyInfo);
                dynamicCommentInfoRedisDao.incrementDynamicCommentReplyNumber(commentReplyInfo.getReplyFromUserId());
                //发送im
                sendCommentReplyIM(commentReplyInfo, json);

            }else{
                logger.info("评论回复反垃圾不通过，评论id："+commentReplyInfo.getCommentId()
                        +",评论回复内容："+commentReplyInfo.getReplyContent());
                throw new ConsumeRuntimeException("4113","评论回复内容违规", HttpStatus.BAD_REQUEST);
            }
        }else{
            logger.error("评论回复反垃圾响应异常，状态码:"+code+"，状态描述："+msg+"评论id："+commentReplyInfo.getCommentId()
                    +",评论回复内容："+commentReplyInfo.getReplyContent());
        }


    }

    /**
     * 发送回复im消息
     * @param commentReplyInfo
     * @param json
     */

    private void sendCommentReplyIM(CommentReplyInfo commentReplyInfo, JSONObject json) {
        logger.info("回复信息："+JSONObject.toJSONString(commentReplyInfo));
        if(!commentReplyInfo.getReplyToUserId().equals(commentReplyInfo.getReplyFromUserId())) {
            long fromUserId = commentReplyInfo.getReplyFromUserId();
            UserCacheVo fromUser = userInfoCache.getUserCacheInfo(fromUserId);
            String fromUserIcon = fromUser.getIcon();

            DynamicCommentInfo dynamiccomment = dynamicCommentInfoRedisDao
                    .getDynamciCommentInfoByCommentId(commentReplyInfo.getCommentId());

            DynamicDetailInfoVo dynamicDetailInfoVo = dynamicInfoRedisDao.getDynamicInfoById(dynamiccomment.getDynamicId());

            long commentId = dynamiccomment.getId();

            long dynamicId = dynamicDetailInfoVo.getDynamicId();

            String dynamicSourceUrl = "";

            DynamicSourceInfoVO dynamicSourceInfoVO = dynamicDetailInfoVo.getDynamicSourceUrls().get(0);
            if (dynamicDetailInfoVo.getSourceType() == 1) {
                dynamicSourceUrl = dynamicSourceInfoVO.getDynamicSourceUrl();
            } else {
                dynamicSourceUrl = dynamicSourceInfoVO.getVideoImgUrl();
            }

            long commentReplyId = commentReplyInfo.getId();

            String message = fromUser.getNickName() + "回复你的评论：" + dynamiccomment.getComment();

            JSONObject ext = new JSONObject();
            ext.put("fromUserId", fromUserId);
            ext.put("fromUserIcon", fromUserIcon);
            ext.put("dynamicId", dynamicId);
            ext.put("commentId", commentId);
            ext.put("commentReplyId", commentReplyId);
//            ext.put("type", 5);
            ext.put("dynamicSourceUrl", dynamicSourceUrl);

            int stat = EnumType.TEXT_MESSAGE.state;
            logger.info("发送回复信息："+ext.toJSONString());
            vestRobotMessageService.getSendMsg(commentReplyInfo.getReplyToUserId(), EnumType.DYNAMIC_USER_ID.state, message,
                    ext.toJSONString(), stat);
        }
    }

    /**
     * 检查用户是否可以回复评论
     * @param userId
     * @param number
     */
    public void checkNumber(long userId, int number) {
        UserCacheVo userInfo = userInfoCache.getUserCacheInfo(userId);

        if(userInfo.getIsVip()!=1&& userInfo.getIsHost()!=1 && userInfo.getIsSvip()!=1 && userInfo.getIsPlatinumVip()!=1){
            int sendNumber = dynamicCommentInfoRedisDao.getSendCommentReplyNumber(userId);
            if(sendNumber>=number){
                throw new ConsumeRuntimeException("4114","回复评论超出日限", HttpStatus.OK);
            }
        }
    }
}
